#define SERVER_LISTERNER
#include "server_listener.h"
#include "buffer_manager.h"

int add_usr_info(char *msg, char *name)
{
	int len;
	strcpy(msg, name);
	strcat(msg, " :");
	len = strlen(msg);

	return len;
}

void *server_listener(void *arg)
{
	int	usr_id = *(int *)arg;
	int 	sock_id = usr[usr_id].sock_id;
	int	len;
	int	offset;
	char	msg[MAX_MSG_SIZE];
	char 	goodbye[] = "goodbye!\n";
	
	offset = add_usr_info(msg, usr[usr_id].name);
	
	do{
		len = read(sock_id, msg + offset, MAX_MSG_SIZE - offset);
		msg[len + offset] = '\0';
		add_to_buffer(msg);
	}while (len > 0);
	
	//user logout
	pthread_mutex_lock(&usr_lock);
	usr[usr_id].active = false;
	sock_list.remove(sock_id);
	usr_num--;
	close(sock_id);
	pthread_mutex_unlock(&usr_lock);

	printf("> user %s logout\n", usr[usr_id].name);
	printf("> current online user number: %d\n", usr_num);
	printf("> waiting...\n");
	add_to_buffer(goodbye);
}

